package com.bosicloud.cmb.ibp.aws.adapter.component.notify.impl;

import com.alibaba.fastjson.JSONObject;
import com.bosicloud.cmb.ibp.aws.adapter.component.notify.NotifyService;
import com.bosicloud.cmb.ibp.commom.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.util.Optional;

/**
 * @author Jack Peng / ziliang.peng@bosicloud.com
 */
@Slf4j
public class SubscriptionConfirmationImpl implements NotifyService {

    private String content;

    public SubscriptionConfirmationImpl(String content) {
        this.content = content;
    }

    @Override
    public void exec() {

        JSONObject obj = JSONObject.parseObject(content);

        Optional<String> subscribeURL = Optional.ofNullable(obj.getString("SubscribeURL"));

        if(subscribeURL.isPresent() && !subscribeURL.get().isEmpty()) {

            if(log.isTraceEnabled()) {
                log.trace("推后5秒处理订阅.");
                try {
                    Thread.sleep(1000 * 5);
                } catch (InterruptedException e) {
                }
                log.trace("开始接收订阅.");
            }

            CloseableHttpClient httpCilent = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(subscribeURL.get());
            try {
                httpCilent.execute(httpGet);
            } catch (IOException e) {
                log.error("确认订阅失败", e);
                throw new BusinessException("确认订阅失败");
            }finally {
                try {
                    httpCilent.close();
                } catch (IOException e) {
                    //
                }
            }
        } else {
            throw new BusinessException("没有发现订阅确认URL.");
        }

    }
}
